package com.oromwin.repos.thread;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.oromwin.repos.common.Common;
import com.oromwin.repos.thread.ProcessManager.LockObject;
import com.oromwin.repos.thread.ProcessManager.Request;

public class ProcessThread extends Thread {
    private int _fid = 0;
    private String _fname = "";
    private int _millis = 5 * 1000;
    private LockObject _lockObject = null;
    private Request _req = null;
    private static Map<Integer,LockObject> _lock = new HashMap<Integer, LockObject>();
    
    public ProcessThread(Request req, Map<Integer, LockObject> lock, LockObject lockObject) {
        _req = req;
        _fid = req.getFid();
        _fname = req.getFname();
        _lock = lock;
        _lockObject = lockObject;
    }
    
    public void run() {
        // process read or write
        synchronized (_lockObject) {
            try {
                if (_req.getlockType() == Common.LockType.READ) {
                    File f = new File(_fname); // 하나의 파일만 읽음
                    FileReader fr = new FileReader(f);
                    char[] cbuf = new char[1024];
                    fr.read(cbuf);
                    System.out.println(_req.toString());
                    System.out.println(String.format("processing... %dsec", _millis / 1000));
                    Thread.sleep(_millis);
                    fr.close();
                } else if (_req.getlockType() == Common.LockType.WRITE) {
                    File f = new File(ProcessManager.getDatetime()); // 매번 새로 생성
                    FileWriter fw = new FileWriter(f);
                    fw.write(ProcessManager.getDatetime());
                    System.out.println(_req.toString());
                    System.out.println(String.format("processing... %dsec", _millis / 1000));
                    Thread.sleep(_millis);
                    fw.close();
                } else {
                    System.out.println("illegal locktype .. exit system");
                    System.exit(-1);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                _lock.remove(_fid);
                System.out.println("\ncompleted.");
            }
        }
    }
}
